package com.springboot.springbootswagger.config;

import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletResponse;

/**
 * @author wangning
 * @create 2021-04-01 16:48
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Autowired
	@Qualifier("authenticationSuccessHandler")
	private AuthenticationSuccessHandler authenticationSuccessHandler;

	@Override
	public void configure(WebSecurity web) throws Exception {
//		web.ignoring()
//				.antMatchers("/user/**");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//开启跨域访问
		http.cors().disable();
		//开启模拟请求，比如API POST测试工具的测试，不开启时，API POST为报403错误
		http.csrf().disable();

		http
				//未登录处理
        		.exceptionHandling()
				.authenticationEntryPoint((request, response, e) -> {
					response.setContentType("application/json;charset=utf-8");
					response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
					response.getWriter()
							.write(("未登录"));
				})
				.and()
				.formLogin().loginProcessingUrl("/login")
				//登录成功处理
				.successHandler(authenticationSuccessHandler)
				.and()
				//拦截规则
				.authorizeRequests()
				.anyRequest().authenticated();


	}
	/**
	 * 密码的加密方式
	 *
	 * @return
	 */
	@Bean
	public PasswordEncoder getPasswordEncoder() {
		return new BCryptPasswordEncoder();
	}
}
